package com.study.juc.cf;

import java.util.concurrent.*;

/**
 * @program: juc-study
 * @author: Zhoujian
 * @date: 2022-08-11 14:34
 * @version: 1.0
 * @description:  入门演示，使用线程池用完一定要记得关闭 threadPool.shutdown() 不然程序会一直是挂起状态，不会停止
 **/
public class CompletableFutureDemo {
	public static void main(String[] args) throws ExecutionException, InterruptedException{

		// 无返回值
		CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
			System.out.println(Thread.currentThread().getName()+"\t"+"-----come in");
			//暂停几秒钟线程
			try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
			System.out.println("-----task is over");
		});
		System.out.println(future.get());

		ExecutorService threadPool = Executors.newFixedThreadPool(2);

		CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
			System.out.println(Thread.currentThread().getName()+"\t"+"-----come in");
			//暂停几秒钟线程
			try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
			System.out.println("-----task is over");
		},threadPool);
		System.out.println(future1.get());


		// 有返回值
		CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
			System.out.println(Thread.currentThread().getName() + "\t" + "-----come in");
			//暂停几秒钟线程
			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return ThreadLocalRandom.current().nextInt(100);
		});

		System.out.println(completableFuture.get());

		CompletableFuture<Integer> completableFuture1 = CompletableFuture.supplyAsync(() -> {
			System.out.println(Thread.currentThread().getName() + "\t" + "-----come in");
			//暂停几秒钟线程
			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return ThreadLocalRandom.current().nextInt(100);
		});

		System.out.println(completableFuture1.get());
		threadPool.shutdown();
	}

}
